<?php
/**
 * Skyline :: Patterns & component framework
 * Copyright 2010-2011 Ian Unruh (Xerof3ar)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Skyline\Comparator;
use Skyline\Structure\Sequence\ArrayList;

/**
 * <b>Composite pattern</b> implementation of ComparatorInterface
 * 
 * This comparator can be used to build powerful multi-sort expressions, much 
 * like in SQL; combine with ValueBoundComparator for best results.
 * 
 * @author Ian Unruh (Xerof3ar) <ianunruh@gmail.com>
 * @since Class avaliable since release 1.0
 */
class CompositeComparator implements ComparatorInterface
{
	/**
	 * @var ArrayList<ComparatorInterface>
	 */
	protected $comparators;
	
	/**
	 * Class constructor
	 * @return void
	 */
	public function __construct()
	{
		$this->comparators = new ArrayList();
	}
	
	/**
	 * Compares a left value to a right value and returns an integer comparison
	 * 
	 * @param mixed $left
	 * @param mixed $right
	 * @return int (-1 = less than, 0 = equal, 1 = greater than)
	 */
	public function compare($left, $right)
	{
		foreach($this->comparators as $comparator) {
			$comparison = $comparator->compare($left, $right);
			if($comparison !== 0) {
				return $comparison;
			}
		}
		return 0;
	}
	
	/** 
	 * @param ComparatorInterface $comparator
	 * @return void
	 */
	public function addComparator(ComparatorInterface $comparator)
	{
		$this->comparators->add($comparator);
	}
	
	/** 
	 * @param ComparatorInterface $comparator
	 * @return void
	 */
	public function removeComparator(ComparatorInterface $comparator)
	{
		$this->comparators->remove($comparator);
	}
	
	/**
	 * @return ArrayList<ComparatorInterface>
	 */
	public function getComparators()
	{
		return $this->comparators;
	}
}